#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import asyncio
from asyncio.queues import Queue, QueueEmpty
from random import randint


msg = Queue(maxsize=50)
consumers = Queue(maxsize=10)


async def producer():
    n = 100
    while n > 0:
        await asyncio.sleep((randint(2, 3)) / 10)
        await msg.put(n)
        print("produce 生产:", n)
        n -= 1


async def make_consumer(timeout=5):
    t = timeout
    n = 1
    while t > 0:
        if msg.qsize() > 0:
            print("创建 consumer{}".format(n))
            await consumer(n)
            n += 1
            t = timeout
            await asyncio.sleep(2)
        else:
            await asyncio.sleep(1)
            t -= 1
    print("{}秒内没有可消费数据，停止生产消费者".format(timeout))


async def consumer(n):
    while True:
        await asyncio.sleep((randint(5, 9)) / 10)
        try:
            r = msg.get_nowait()
            print("consumer{} 消费: {}".format(n, r))
            await make_consumer()
        except QueueEmpty:
            print("consumer{} 停止".format(n))


loop = asyncio.get_event_loop()
tasks = [make_consumer(), producer()]
loop.run_until_complete(asyncio.wait(tasks))
